/*
 * @lc app=leetcode.cn id=24 lang=java
 *
 * [24] 两两交换链表中的节点
 */

// @lc code=start
/**
 * Definition for singly-linked list. public class ListNode { int val; ListNode
 * next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val,
 * ListNode next) { this.val = val; this.next = next; } }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {

        if (head == null || head.next == null) {
            return head;
        }

        ListNode h = new ListNode(-1);
        h.next = head;
        ListNode pre = h;
        ListNode cur;
        ListNode next;

        for (int i = 0;; i++) {
            cur = pre.next;
            next = cur.next;
            if (next == null) {
                break;
            }
            pre.next = next;
            cur.next = next.next;
            boolean stop = next.next == null;
            next.next = cur;
            if (stop) {
                break;
            }
            pre = cur;
        }
        return h.next;
    }
}
// @lc code=end
